<template>
  <div
    class="w-[350px] border border-gray-200 bg-white p-3 shadow-md rounded-lg"
    @click="openDrawer"
  >
    <Handle type="target" :position="Position.Left" />
    <div class="flex flex-col gap-y-1">
      <common-title-module />
      <CommonDisplayModule title="输入" value-name="vartype" :valueList="data?.inoutlist" />
      <CommonDisplayModule title="输出" value-name="vartype" :valueList="data?.commonoutvo" />
    </div>
    <Handle type="source" :position="Position.Right" />
  </div>
  <QueueDrawerModule
    ref="drawerRef"
    addInputBtn
    :formKeys="formKeys"
    :title="node?.node?.label"
    desc="用于给支持写入的变量赋值，包括应用变量、用户变量"
    :form="data"
    @add="handleClickAddBtn"
    @remove="handleClickDeleteBtn"
    @cancel="onCancel"
  />
</template>
<script setup>
import { ref } from 'vue'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'

import CommonTitleModule from '../modules/common-title-module.vue'
import CommonDisplayModule from '../modules/common-display-module.vue'
import HttprequestDrawerModule from '../modules/httprequest-drawer-module.vue'

const formKeys = {
  inputKey: 'inoutlist',
  ouputKey: 'commonoutvo'
}

const node = useNode()

const data = ref({
  answer: '',
  type: 0,
  flowOutput: false,
  prompts: '',
  outputFormat: 'text',
  inoutlist: node.node.data?.inoutlist ||[],
  commonoutvo: [
    {
      varname: 'isSuccess',
      vartype: 'Boolean'
    }
  ]
})

const drawerRef = ref(null)
const openDrawer = () => {
  drawerRef.value?.init()
}

function handleClickAddBtn(listKey) {
  data.value[listKey].push({
    varname: '',
    varparam: '',
    vartype: 'String'
  })
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

function handleClickDeleteBtn(listKey, index) {
  data.value[listKey].splice(index, 1)
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

const onCancel = () => {
  editNode({
    data: {
      id: node.id,
      ...data.value,
      commonoutvo: data.value.commonoutvo.reduce((pre, cur) => {
        let childrenObj = {}
        if(cur.children) {
          childrenObj = cur.children.reduce((val, row)=>{
            return {
              ...val,
              [row.varname]: row.vartype
            }
          }, {})
        }

        return {
          ...pre,
          [cur.varname]: cur.vartype,
          ...childrenObj
        }
      }, {})
    }
  })
}
</script>
